package Classic150;

import LinkedList.ListNode;

public class 合并两个有序链表 {
    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        /*
            递归实现，注意分析为什么可以使用递归，分解问题
         */
        if (list1 == null) return list2;
        else if (list2 == null) return list1;
        else if (list1.val <= list2.val) {
            list1.next = mergeTwoLists(list1.next, list2);
            return list1;
        } else {
            list2.next = mergeTwoLists(list1, list2.next);
            return list2;
        }

        /*
            迭代实现，注意虚拟头节点的巧用
         */
        /*ListNode root = new ListNode(-1);
        ListNode cur = root;
        while (list1 != null && list2 != null) {
            if (list1.val < list2.val) {
                cur.next = list1;
                list1 = list1.next;
            } else {
                cur.next = list2;
                list2 = list2.next;
            }
            cur = cur.next;
        }
        cur.next = list1 == null ? list2 : list1;
        return root.next;*/
    }
}
